//
//  SYS_MessageContactVC.m
//  System_App
//
//  Created by czy001 on 2017/12/1.
//  Copyright © 2017年 czy001. All rights reserved.
//

#import "SYS_MessageContactVC.h"
#import "SYS_MessageHomeCell.h"
#import "SYS_StoreContactView.h"

@interface SYS_MessageContactVC ()<SYS_StoreContactViewDelegate,SYS_SearchViewDelegate,UIWebViewDelegate>
@property (nonatomic,strong) UIWebView *webView;
//搜索视图
@property (nonatomic, strong) SYS_SearchView *searchView;

@property (nonatomic, strong) SYS_DisplayWithBlankView *alertView;

@property (nonatomic, strong) SYS_StoreContactView *storeListView;

@end

@implementation SYS_MessageContactVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor=RGBACOLOR(242, 242, 242, 1);
    
    [self initData];
    
    [self viewDisplay];
    
    [self getStoreMembersList];
}

//初始数据
- (void)initData
{
    _dataArr=[[NSMutableArray alloc] init];
    session=[SYS_LoginModel instance].sessionInfo.session;
    page=1;
    
    UICKeyChainStore *keychainStore = [UICKeyChainStore keyChainStore];
    pid = [keychainStore stringForKey:@"pid"];
}

- (void)viewDisplay
{
    _webView=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT-TabBarHeight-NavBarHeight-45)];
    _webView.scrollView.showsHorizontalScrollIndicator=NO;
    _webView.scrollView.showsVerticalScrollIndicator=NO;
    _webView.delegate=self;
    _webView.dataDetectorTypes = UIDataDetectorTypeNone;
    _webView.backgroundColor=DGHColor(242,242 , 242);
    [self.view addSubview:_webView];
    //    NSString *session=[SYS_LoginModel instance].sessionInfo.session;
    //    UICKeyChainStore *keychainStore = [UICKeyChainStore keyChainStore];
    //    NSString *pid = [keychainStore stringForKey:@"pid"];
    //    NSURL *url = [NSURL URLWithString:FORMAT(@"http://118.178.188.69:8081/index.html#/store/?session=%@&pid=%@", session,pid)];
    NSURL *url = [NSURL URLWithString:FORMAT(@"http://118.178.188.69:8081/index.html#/message/employee/addressBook")];
    NSString *body=nil;
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
    [request setHTTPMethod: @"GET"];
    [request setHTTPBody: [body dataUsingEncoding:NSUTF8StringEncoding]];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
    [_webView loadRequest: request];
//    _searchView = [[SYS_SearchView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 40)];
//    _searchView.isClickChange=YES;
//    _searchView.placeholder=@"请输入您要查找的联系人";
//    _searchView.delegate=self;
//    [self.view addSubview:_searchView];
//
//    _storeListView=[[SYS_StoreContactView alloc] initWithFrame:CGRectMake(0, 40, SCREENWIDTH, 49)];
//    _storeListView.delegate=self;
//    [self.view addSubview:_storeListView];
//
//    _mainTableView=[[SYS_TableView alloc] initWithFrame:CGRectMake(0, 90, self.view.frame.size.width, SCREENHEIGHT-45-NavBarHeight-TabBarHeight-90) style:UITableViewStylePlain];
//    _mainTableView.dataSource=self;
//    _mainTableView.delegate=self;
//    _mainTableView.backgroundColor=[UIColor clearColor];
//    _mainTableView.backgroundView=nil;
//    _mainTableView.sectionIndexBackgroundColor=[UIColor clearColor];
//    //    _mainTableView.scrollEnabled=NO;
////    _mainTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
//
//    [_mainTableView registerNib:[UINib nibWithNibName:@"SYS_MessageHomeCell" bundle:nil] forCellReuseIdentifier:@"SYS_MessageHomeCell"];
//
//    [self.view addSubview:_mainTableView];
//
//    //下拉刷新数据
//    _mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        page=1;
//        [self getStoreMembersList];
//
//        [_mainTableView.mj_header endRefreshing];
//    }];
//
//    _mainTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
//
//        if (_dataArr.count % 10 == 0 && !isLast) {
//            page++;
//            [self getStoreMembersList];
//        }
//        else
//        {
//            [MBProgressHUD showSuccess:@"当前页已是最新" toView:self.view];
//        }
//        [_mainTableView.mj_footer endRefreshing];
//
//    }];
    
}

#pragma mark ---SYS_SearchViewDelegate----
- (void)goSearchResultVC
{
    if (_delegate && [_delegate respondsToSelector:@selector(goSearchMember)]) {
        [_delegate goSearchMember];
    }
}

#pragma mark ----SYS_StoreContactViewDelegate---
- (void)buttonClickTapToStoreList
{
    if (_delegate && [_delegate respondsToSelector:@selector(goStoreList)]) {
        [_delegate goStoreList];
    }
}

#pragma mark tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (CGFloat)cellContentViewWith
{
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    
    // 适配ios7
    if ([UIApplication sharedApplication].statusBarOrientation != UIInterfaceOrientationPortrait && [[UIDevice currentDevice].systemVersion floatValue] < 8) {
        width = [UIScreen mainScreen].bounds.size.height;
    }
    return width;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SYS_MemberModel *model=_dataArr[indexPath.row];
    if (_delegate && [_delegate respondsToSelector:@selector(didSelectMember:)]) {
        [_delegate didSelectMember:model];
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier=@"SYS_MessageHomeCell";
    SYS_MessageHomeCell *cell=(SYS_MessageHomeCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell==nil) {
        cell=[[SYS_MessageHomeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    SYS_MemberModel *model=_dataArr[indexPath.row];
    cell.model=model;
    //点击Cell时背景不变蓝
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
    return cell;
}

#pragma mark 设置可以进行编辑

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

{
    return YES;
}

/**
 
 *  tableView:editActionsForRowAtIndexPath:     // 设置滑动删除时显示多个按钮
 
 *  UITableViewRowAction                        // 通过此类创建按钮
 
 *  1. 我们在使用一些应用的时候，在滑动一些联系人的某一行的时候，会出现删除、置顶、更多等等的按钮，在iOS8之前，我们都需要自己去实现。But，到了iOS8，系统已经写好了，只需要一个代理方法和一个类就搞定了
 
 *  2. iOS8的<UITableViewDelegate>协议多了一个方法，返回值是数组的tableView:editActionsForRowAtIndexPath:方法，我们可以在方法内部写好几个按钮，然后放到数组中返回，那些按钮的类就是UITableViewRowAction
 
 *  3. 在UITableViewRowAction类，我们可以设置按钮的样式、显示的文字、背景色、和按钮的事件（事件在Block中实现）
 
 *  4. 在代理方法中，我们可以创建多个按钮放到数组中返回，最先放入数组的按钮显示在最右侧，最后放入的显示在最左侧
 
 *  5. 注意：如果我们自己设定了一个或多个按钮，系统自带的删除按钮就消失了...
 
 */

#pragma mark 在滑动手势删除某一行的时候，显示出更多的按钮

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        //    // 删除按钮
        SYS_MemberModel *model=_dataArr[indexPath.row];
        
        UITableViewRowAction *contactRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"发送消息" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
            
            if (_delegate && [_delegate respondsToSelector:@selector(didSelectMemberToChat:)]) {
                [_delegate didSelectMemberToChat:model];
            }
        }];
        contactRowAction.backgroundColor = RGBACOLOR(244, 52, 75, 1);
        
        UITableViewRowAction *callRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"拨打电话" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){
            
            NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",model.phone];
            UIWebView * callWebview = [[UIWebView alloc] init];
            [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
            [self.view addSubview:callWebview];
        }];
        callRowAction.backgroundColor = RGBACOLOR(191, 191, 191, 1);
        
        
        return @[contactRowAction,callRowAction];
    }
    return nil;
}

#pragma mark -----Request---
- (void)getStoreMembersList
{
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    [dic setValue:@(page) forKey:@"pageNumber"];
    [dic setValue:@(PAGE_LENGTH) forKey:@"pageSize"];
    [dic setValue:session forKey:@"session"];
    [dic setValue:pid forKey:@"pid"];
    
    [SYS_HttpUtility getMemberListRequest:dic success:^(id returnValue) {
        if ([returnValue[@"flag"] isEqualToString:@"true"]) {
            if (page == 1) {
                [_dataArr removeAllObjects];
            }
            NSArray *array=returnValue[@"data"][@"list"];
            if (array.count>0) {
                isLast=NO;
            }
            else
            {
                isLast=YES;
            }
            for (int i=0; i<array.count; i++) {
                SYS_MemberModel *model=[SYS_MemberModel mj_objectWithKeyValues:array[i]];
                [_dataArr addObject:model];
            }
            [_mainTableView reloadData];
        }
        else
        {
             [MBProgressHUD showSuccess:returnValue[@"exp"] toView:self.view];
        }
    } failure:^{
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        RequestFailure;
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
